package com.nie.mall.gateway.filter;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.mall.admin.entity.UmsAdmin;
import com.mall.common.constant.CommonConst;
import com.mall.common.domain.TokenDomain;
import com.nie.mall.gateway.config.properties.WhiteListProperties;
import com.nie.mall.gateway.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHeaders;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    @Resource
    private WhiteListProperties whiteListProperties;
    @Resource
    private ResponseUtil responseUtil;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.debug("请求路径：{}",exchange.getRequest().getPath());
        if (checkWhiteUrl(exchange)) {
            return chain.filter(exchange);
        }
        if (checkNoToken(exchange)) {
            return ResponseUtil.returnMono(exchange.getResponse(), "令牌不能为空", HttpStatus.UNAUTHORIZED);
        }
        if (checkNoAuth(exchange)) {
            return ResponseUtil.returnMono(exchange.getResponse(), "认证失败", HttpStatus.UNAUTHORIZED);
        }
        ServerHttpRequest request = exchange.getRequest();
        String token = getToken(request);
        String userInfo = stringRedisTemplate.opsForValue().get(TokenDomain.TOKEN_PREFIX + token);
        UmsAdmin umsAdmin = JSONUtil.toBean(userInfo, UmsAdmin.class);

        ServerHttpRequest httpRequest = request.mutate().header(CommonConst.HEADER_TENANT_ID, umsAdmin.getTenantId())
                .header(CommonConst.HEAD_USER_ID, umsAdmin.getId())
                .build();

        return chain.filter(exchange.mutate().request(httpRequest).build());
    }

    private boolean checkNoAuth(ServerWebExchange exchange) {
        List<String> stringList = exchange.getRequest().getHeaders().get(HttpHeaders.AUTHORIZATION);
        Assert.notNull(stringList, "token为空");
        for (String token : stringList) {
            if(Boolean.TRUE.equals(stringRedisTemplate.hasKey(TokenDomain.TOKEN_PREFIX+token))){
                log.debug("认证成功:{}",token);
                return false;
            }
        }
        return true;
    }

    private boolean checkNoToken(ServerWebExchange exchange) {
        return StrUtil.isBlank(getToken(exchange.getRequest()));
    }

    /**
     * 检查白色url
     *
     * @param exchange 交换
     * @return boolean
     */
    private boolean checkWhiteUrl(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        AntPathMatcher pathMatcher = new AntPathMatcher();
        List<String> urls = whiteListProperties.getListUrl();
        for (String url : urls) {
            if (pathMatcher.match(url, path)) {
                log.info("白名单处理:{}", path);
                return true;
            }
        }
        return false;
    }

    /**
     * 获取令牌
     *
     * @param request 请求
     * @return {@code String}
     */
    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (StrUtil.isNotBlank(token) && token.startsWith("bear")) {
            token = token.replaceFirst("bear", token);
        }
        return token;
    }
    @Override
    public int getOrder() {
        return -200;
    }
}
